package controllers

import (
	"gameTest/common"
	"gameTest/datamodels"
	"gameTest/services"
	"github.com/kataras/iris"
	"time"
)

type UserController struct {
	Ctx     iris.Context
	Service services.IUserService
}

func (c *UserController) PostRegister() datamodels.Result {
	//获取post表单值
	var (
		nickName = c.Ctx.FormValue("nickname")
		userName = c.Ctx.FormValue("username")
		password = c.Ctx.FormValue("password")
	)
	//赋值
	user := &datamodels.User{
		NickName:     nickName,
		UserName:     userName,
		HashPassword: password,
	}
	errValid := user.RegisterValidate()
	if errValid != nil {
		return common.BuildResult(400, "测试err", errValid)
	}

	user.CreateAt = time.Now().Format("2006-01-02 15:04:05")
	user.UpdateAt = user.CreateAt
	_, err := c.Service.AddUser(user)
	//连接数据库
	if err != nil {
		return common.BuildResult(400, "失败", err)
	}
	return common.BuildResult(200, "注册成功", "")
}

func (c *UserController) GetUser() datamodels.Result {
	data := common.BuildResult(200, "成功", "")
	return data
}

//验证数据用ozzo-validtation

func (c *UserController) PostLogin() datamodels.Result {
	var (
		userName = c.Ctx.FormValue("username")
		password = c.Ctx.FormValue("password")
	)
	//fmt.Println(userName)
	//fmt.Println(password)

	////连接数据库
	//db, err := common.NewMysqlConn()
	//if err != nil {
	//	log.Error(err)
	//}
	//repository := repositories.NewUserRepository("user", db)
	//user, errSelect := repository.Select(userName)
	//if errSelect != nil {
	//	return common.BuildResult(400, "错误信息", user)
	//}
	//return common.BuildResult(200, "查询的用户", user)
	user, ok := c.Service.IsPwdSuccess(userName, password)
	if !ok {
		return common.BuildResult(400, "账户名不存在或者密码错误", "")
	}
	return common.BuildResult(200, "登录成功", user.AuthToken)

}
